#!/usr/bin/env python

# subflip - Prepare subtitle files for non-bidi-aware players.
# Copyright (C) 2006 Noam Raphael < spam.noam at gmail.com >
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA


"""
This little program is used to generate the cdata.py files, which gives
directionality data for characters. It makes it from the file UnicodeData.txt,
available from http://unicode.org/Public/UNIDATA/UnicodeData.txt
"""

def read_ucd(f):
    r = {}
    for line in f:
        s = line.split(';')
        r[unichr(int(s[0],16))] = s[1:-1]
    return r

mytypes = {
    # Neutral characters
    'ON'  : 'N',
    'B'   : 'N',
    'BN'  : 'N',
    'S'   : 'N',
    'WS'  : 'N',
    # RTL characters. This includes NSM, since in cp1255, it's only nikud.
    # if someone uses it after an LTR char the standard says it should become
    # LTR too, but - if someone tries to add nikud to English chars, it's
    # his problem.
    'R'   : 'R',
    'NSM' : 'R',
    # LTR characters
    'L'   : 'L',
    # Numeric types - EN (European Number), T (Number Terminator),
    #                 S (Number seperator).
    'EN'  : 'EN',
    'ET'  : 'T',
    'ES'  : 'S',
    'CS'  : 'S',
}

def make_dict(ucd):
    r = {}
    for byte in range(256):
        try:
            c = chr(byte).decode('cp1255')
        except UnicodeDecodeError:
            continue

        r[c] = mytypes[ucd[c][3]]
    return r

def make_mapping(input, output):
    '''
    Get the input file, which should be the file UnicodeData.txt, and write
    to the output file a Python module which defines the dict which maps
    each character in the cp1255 encoding to its type.
    '''
    ucd = read_ucd(input)
    d = make_dict(ucd)
    print >> output, '''\
# Character data for the bidi algorithm.
# Autogenerated from UnicodeData.txt, by generate_cdata.py

cdata = {'''
    chars = sorted(d.keys())
    for c in chars:
        print >> output, '    %r : %r,' % (c, d[c])
    print >> output, '}'

def main():
    import sys

    if len(sys.argv) != 1:
        print >> sys.stderr, 'Usage: %s < UnicodeData.txt > cdata.py'\
              % (sys.argv[0])
        sys.exit(1)

    make_mapping(sys.stdin, sys.stdout)

if __name__ == '__main__':
    main()
